package com.mrd.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.github.pagehelper.PageHelper;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE,
    sqlSessionFactoryRef = "sqlSessionFactory")
public class MasterDataSourceConfig {

  // 精确到 master 目录，以便跟其他数据源隔离
  static final String PACKAGE = "com.mrd.modules.*.dao";
  static final String MAPPER_LOCATION = "classpath:mapper/*.xml";
  private static String MYBATIS_CONFIG = "mybatis.xml";

  @Bean(name = "transactionManager")
  @ConditionalOnMissingBean(PlatformTransactionManager.class)
  @Primary
  public DataSourceTransactionManager masterTransactionManager(
      @Qualifier("dataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "sqlSessionFactory")
  @Primary
  public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)
      throws Exception {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));
    sessionFactory.setDataSource(dataSource);
    sessionFactory.setVfs(SpringBootVFS.class);
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources(MasterDataSourceConfig.MAPPER_LOCATION));
    // 分页插件
    PageHelper pageHelper = new PageHelper();
    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    pageHelper.setProperties(props);
    // 添加插件
    sessionFactory.setPlugins(new Interceptor[] {pageHelper});
    return sessionFactory.getObject();
  }
}
